<?php
/**
 * 签到 记录
 */

namespace app\api\model;


use app\common\model\Model;
use think\Db;

class SignInRecord extends Model
{
    const TABLE_NAME = 'sign_in_record';
    const CACHE_EXPIRE_LEVEL = self::CACHE_EXPIRE_LEVEL_4;

    protected $name = self::TABLE_NAME;

    public static function addRecord($user_id)
    {
        $today = get_today_timestamp();
        Db::startTrans();

        try{
            $sql="select record_id from sign_in_record where record_user_id = $user_id and record_time >= $today limit 1 for update";
            $info = self::query($sql);
            if(!empty($info))
            {
                Db::rollback();
                return ['status'=>false, 'msg'=>'今日已签到'];
            }

            $record_id= self::insert(['record_user_id'=>$user_id,'record_time'=>time()],false,true);

            User::incrUserPoints($user_id,PointsRecord::NUM_SIGN_IN);

            PointsRecord::addRecord($user_id,PointsRecord::POINTS_SIGN_IN,$record_id,PointsRecord::NUM_SIGN_IN);
        }catch (\Exception $e)
        {
            Db::rollback();
            return ['status'=>false,'msg'=>$e->getMessage()];
        }
        self::updateUserContinueSign($user_id);
        Db::commit();
        return ['status'=>true,'msg'=>''];
    }

    // 更新 用户连续签到天数
    private static function updateUserContinueSign($user_id)
    {
        $month =date('Ym');
        $day=date('j');
        $month_day_num =date('t');
        
        $query_sql="select * from sign_in_continue where user_id=$user_id order by sign_month desc limit 1 for update";

        $info = self::query($query_sql);

        $update_sql="insert into sign_in_continue(`user_id`,`sign_month`,`last_date`,`total_sign_day`,`continue_sign_day`) VALUES($user_id,$month,$day,1,1) on duplicate key update last_date=$day,total_sign_day=total_sign_day+1";

        self::execute($update_sql);
        //与 上个月 是否为连续 签到
        $is_continue_sign=true;
        if(!empty($info) && $info[0]['sign_month'] == $month)
        {
            if($info[0]['last_date'] + 1 == $day)
            {
                //今天与昨天 连续签到
                self::commonQuery('sign_in_continue')->where(['user_id'=>$user_id,'sign_month'=>$month])
                     ->setInc('continue_sign_day');
                //满月签到
                if($month_day_num == $info[0]['continue_sign_day'] +1){
                    
                    User::incrUserPoints($user_id,PointsRecord::NUM_MONTH_SIGN_IN);

                    PointsRecord::addRecord($user_id,PointsRecord::POINTS_MONTH_SIGN_IN,$month,PointsRecord::NUM_MONTH_SIGN_IN);
                }
                //当前月 是否 为连续签到
                $is_continue_sign = $day == $info[0]['continue_sign_day'] +1;
               
                
            }else{
                $is_continue_sign=false;
                //当前月连续签到天数 设置为 1
                self::commonQuery('sign_in_continue')->where(['user_id'=>$user_id,'sign_month'=>$month])
                    ->setField('continue_sign_day',1);
            }
        }
        //判断 是否满 300 天连续签到签到 
        if($is_continue_sign)
        {
           self::handleThreeHundredSignIn($user_id);
        }else{
            // 从1开始计数
            self::commonQuery('sign_in_total_continue')->where(['user_id'=>$user_id])
                 ->setField('sign_day',1);
        }
    }

    private static function handleThreeHundredSignIn($user_id)
    {
        $sql="select * from sign_in_total_continue where user_id =$user_id for UPDATE ";
        $info = self::query($sql);

        $update_sql="insert into sign_in_total_continue(`user_id`,`sign_day`) VALUES($user_id,1) on duplicate key update sign_day=sign_day+1";
        self::execute($update_sql);
        if(!empty($info) && $info[0]['sign_day'] + 1 == 4)
        {
            $today =date('Ymd');
            User::incrUserPoints($user_id,PointsRecord::NUM_THREE_HUNDRED_DAY_SIGN_IN);

            PointsRecord::addRecord($user_id,PointsRecord::POINTS_THREE_HUNDRED_DAY_SIGN_IN,$today,PointsRecord::NUM_THREE_HUNDRED_DAY_SIGN_IN);

            //从 0 开始计数
            self::commonQuery('sign_in_total_continue')->where(['user_id'=>$user_id])
                ->setField('sign_day',0);
        }
    }

    //当前月 签到 日期
    public static function getSignInRecordDay($user_id)
    {
        $month=date("Ym");

        $month_date= date_create($month."01");
        $start_time=date_format($month_date,"U");
        date_add($month_date, date_interval_create_from_date_string("1 months"));
        $end_time=date_format($month_date,"U") -1;

        $list = self::commonQuery(self::TABLE_NAME)
               ->where(['record_user_id'=>$user_id,'record_time'=>['between',[$start_time,$end_time]]])
               ->select();
        $res=[];
        foreach ($list as $key=>$val)
        {
            $res[]=date('j',$val['record_time']);
        }
        return $res;
    }
}

